/*
 * Copyright 2013 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.madding.shared.encrypt.io;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;

import com.madding.shared.encrypt.constants.Charset;
import com.madding.shared.encrypt.log.LogAgg;

/**
 * 类StreamUtil.java的实现描述：TODO 类实现描述
 * 
 * @author madding.lip Nov 17, 2013 11:17:53 PM
 */
public class StreamUtil {

    public static byte[] stream2Bytes(InputStream is) throws IOException {
        int total = is.available();
        byte[] bs = new byte[total];
        is.read(bs);
        return bs;
    }

    public static String stream2Bytes(InputStream is, Charset charset) {
        String result = null;
        try {
            int total = is.available();
            byte[] bs = new byte[total];
            is.read(bs);
            result = new String(bs, charset.getCharset());
        } catch (UnsupportedEncodingException e) {
            LogAgg.util.error(LogAgg.getFalseMsg(result, "byte to string error, errormsg=" + e.getMessage()));
        } catch (IOException e) {
            LogAgg.util.error(LogAgg.getFalseMsg(result, "byte to string error, errorMsg=" + e.getMessage()));
        }
        return result;
    }

    public static InputStream bytes2Stream(byte[] bs) {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bs);
        return inputStream;
    }

    public static InputStream bytes2Stream(String text, Charset charset) throws UnsupportedEncodingException {
        ByteArrayInputStream inputStream = null;
        if (StringUtils.isBlank(text)) {
            return null;
        }
        byte[] bs = text.getBytes(charset.getCharset());
        inputStream = new ByteArrayInputStream(bs);
        return inputStream;
    }

    public String reader2String(InputStream is) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = " ";
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }
}
